/**
 * 群组管理初始化
 */
var Group = {
    id: "GroupTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    ztree: null,
    layerIndex: -1
};

/**
 * 点击添加群组
 */
Group.openAddGroup = function () {
	var ispublic=$("#ispublic").val();
    var index = layer.open({
        type: 2,
        title: '添加群组',
        area: ['600px', '240px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Sys.backendPath + '/group/to_add/'+ispublic,
    });
    this.layerIndex = index;
};

/**
 * 打开查看群组详情
 */
Group.openGroupDetail = function () {
    if (Group.groupId&&Group.groupId!=-1) {
        var index = layer.open({
            type: 2,
            title: '群组详情',
            area: ['600px', '240px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Sys.backendPath + '/group/to_update/' + Group.groupId
        });
        this.layerIndex = index;
    }else{
        Sys.info("请选中要修改的群组！");
    }
};

/**
 * 删除群组
 */
Group.del = function () {
	if (Group.groupId&&Group.groupId!=-1) {
        var operation = function(){
	        var ajax = new $ax(Sys.backendPath + "/group/delete", function (data) {
	        	Group.ztree.init();
	        	GroupMember.table.refresh();
	            Sys.success("删除成功!");
	            Group.groupId=null;
	        }, function (data) {
	            Sys.error("删除失败!" + data.responseJSON.message + "!");
	        });
	        ajax.set("groupId",Group.groupId);
	        ajax.start();
	    };
	    Sys.confirm("是否删除群组?",operation);
	}else{
	    Sys.info("请选中要删除的群组！");
	}
};

/**
 * 点击查看某一群组成员
 */
Group.searchGroupMember = function () {
	var queryData = {};
	queryData['username'] = $("#groupMemberName").val();
    queryData['groupId'] = this.groupId;
    GroupMember.table.refresh({query: queryData});
};
Group.onClickGroup= function (e, treeId, treeNode) {
	Group.groupId=treeNode.id;
    Group.searchGroupMember();
};

/**
 * 显示群组列表
 */
$(function () {
	var params = $("#ispublic").val()+","+$("#createby").val();
    var ztree = new $ZTree("folderTree", Sys.backendPath + "/group/groupTree/"+params);
    ztree.bindOnClick(Group.onClickGroup);
    ztree.init();
    Group.ztree = ztree;
    fuzzySearch('folderTree','#seachKey',null,true);
});


/*                   群组成员信息                                          */

/**
 * 群组成员管理初始化
 */
var GroupMember = {
    id: "GroupMemberTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
GroupMember.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: '组员部门', field: 'dept.name', align: 'center', valign: 'middle', sortable: true},
        {title: '组员名称', field: 'user.name', align: 'center', valign: 'middle', sortable: true},
        {title: '组员手机', field: 'user.phone', align: 'center', valign: 'middle', sortable: true},
        {title: '操作', field: 'id', align: 'center', width: '120px', valign: 'middle',formatter:function(value,row,index){
    		var _html = '<a href="javascript:GroupMember.del(\''+row.id+'\',\''+row.user.name+'\')" title="删除"><i class="fa fa-trash-o"></i></a>';
    		return _html;
        }}];
};

/**
 * 检查是否选中
 */
GroupMember.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Sys.info("请先选中表格中的某一记录！");
        return false;
    }else{
        GroupMember.seItem = selected[0];
        return true;
    }
};


/**
 * 检查是否选中群组
 */
GroupMember.checkGroupId = function () {
   
   if(Group.groupId && Group.groupId != -1){
	   return true;
   }else{
	   Sys.info("请先选中群组！");
       return false;
   }
};



/**
 * 删除群组成员
 */
GroupMember.del = function (id,name) {
	var flag = false;
	if(id){
		flag = true;
	}else if (this.check()) {
        id = this.seItem.id;
        name = this.seItem.user.name
        flag = true;
    }
	if (flag) {
        var operation = function(){
	        var ajax = new $ax(Sys.backendPath + "/member/delete", function (data) {
	            Sys.success("删除成功!");
	            GroupMember.table.refresh();
	        }, function (data) {
	            Sys.error("删除失败!" + data.responseJSON.message + "!");
	        });
	        ajax.set("groupMemberId",id);
	        ajax.start();
	    };
	    Sys.confirm("是否删除群组成员【" + name + "】?",operation);
    }
};

/**
 * 查询群组成员列表
 */
GroupMember.search = function () {
    var queryData = {};    
    queryData['username'] = $("#groupMemberName").val();
    GroupMember.table.refresh({query: queryData});
};

/**
 * 群组成员添加树
 */
GroupMember.showUserSelectTree = function (obj) {
	if (this.checkGroupId()) {
		var _text_id = $(obj).attr("id");
		var _value_id = $(obj).attr("id")+"_id";
		var ids = $("#"+_value_id).val();
		var isMulti = true;
		var opt = {
	            type: 2,
	            title: '选择成员',
	            area: ['300px', '450px'], //宽高
	            fix: false, //不固定
	            maxmin: true,
	            content: '/static/common/_selecttree.html',
	            success: function(layero, index){
	                var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
	                iframeWin.initTree(Sys.backendPath + "/tree/user",isMulti,ids);
	            }
	        }
		opt["btn"]=[];
		opt.btn.push('<i class="fa fa-check"></i> 保存');
		opt['btn'+opt.btn.length] = function(index, layero){
	        var win = window[layero.find('iframe')[0]['name']];
			win.$('#keyword').val('').change();
			var nodes,id="";
			if (isMulti){
				nodes = win.tree.getCheckedNodes(true);
			}else{
				nodes = win.tree.getSelectedNodes();
			}
			id=Group.groupId+",";
			for(var i=0; i<nodes.length; i++) {
				id += nodes[i].id+",";
			}
			console.log(id);
			var ajax = new $ax(Sys.backendPath + "/member/add", function (data) {
				GroupMember.table.refresh();
				Sys.success("添加成功!");
				layer.close(index);
			}, function (data) {
	            Sys.error("添加失败!" + data.responseJSON.message + "!");
	        });    
			ajax.set("user_id",id);
			ajax.start();
		};
	
		opt.btn.push('<i class="fa fa-close"></i> 关闭');
		opt['btn'+opt.btn.length] = function(index, layero){
	        var index = layer.getFrameIndex(layero.find('iframe')[0]['name']); //获取窗口索引
	        layer.close(index);
		};
	
	    layer.open(opt); 
	}
};


/**
 * 显示群员信息
 */
$(function () {
	var defaultColunms = GroupMember.initColumn();//构建groupmember表
	var table = new BSTable(GroupMember.id, Sys.backendPath + "/member/list", defaultColunms);
	table.setSubHeight(-5);
	table.setPaginationType("server");
	GroupMember.table = table.init();
	
    var treeObj = $.fn.zTree.getZTreeObj("folderTree");
    //获取节点,使之显示第一个群组的成员
    var nodes = treeObj.getNodes();
	if (nodes.length>0) {
        var node = treeObj.selectNode(nodes[0]);
        Group.groupId=nodes[0].id;
        Group.searchGroupMember();
	}else{
		Group.groupId=-1;
        Group.searchGroupMember();
	}
});




